<template>
  <div class="attack-container">
    <div class="cesium-container" ref="cesiumRef">
      <div class="toolbox">
        <el-switch
          v-model="showAssetsPanel"
          active-action-icon="View"
          inactive-action-icon="Hide"
          active-text="显示资产"
        />
        <el-switch
          v-model="showThreatPanel"
          active-action-icon="View"
          inactive-action-icon="Hide"
          active-text="显示可打击卫星"
        />
      </div>
      <div id="credit" class="credit"></div>
      <div class="attack-degree">
        <div class="count">
          <div>
            <span>{{ attackCountObj?.strikeDegree.toFixed(3) }}</span
            ><span>整体可打击度</span>
          </div>
          <div>
            <span>{{ attackCountObj?.threatDegree.toFixed(3) }}</span
            ><span>整体威胁度</span>
          </div>

          <div>
            <span>{{ attackCountObj?.days }}</span
            ><span>分析天数</span>
          </div>
        </div>
      </div>
      <transition name="slide">
        <div class="attck-assets" v-show="showAssetsPanel">
          <div class="assets">
            <div class="assets-l">
              <div class="assets-l__title">我方资产列表</div>
              <div class="assets-item" v-for="item in weapons" @click="showAssets">
                <div>
                  <span style="padding-right: 30px; font-size: 16px; font-weight: bold">{{ item.name }}</span>
                </div>
                <div>
                  <span>可打击卫星轨道覆盖 </span>
                  <div class="tag-box">
                    <el-tag type="success" v-for="orbit in item.orbit_coverage">{{ orbit }}</el-tag>
                  </div>
                </div>
                <div>
                  <span>可打击卫星类型覆盖 </span>
                  <div class="tag-box">
                    <el-tag type="success" v-for="sateType in item.suitable_targets">{{ sateType }}</el-tag>
                  </div>
                </div>
                <div>
                  <span>资产部署位置 </span>
                  <el-tag type="primary">{{ item.province }}</el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <div
        class="attck-satellite"
        :style="{ width: showAssetsPanel ? 'calc(100vw - 350px)' : '100vw', left: showAssetsPanel ? '350px' : '0px' }"
        v-show="showThreatPanel"
      >
        <div class="asset-grid-item">
          <el-table style="width: 100%" :data="satelliteStrike">
            <el-table-column prop="norad_id" label="编号" width="180" />
            <el-table-column prop="comprehensive_strike_score" label="可打击度" width="180" sortable />
            <el-table-column prop="int_id" label="国际编号" width="180" />
            <el-table-column prop="name_en" label="卫星名称" />
            <el-table-column prop="threat_score" label="平均威胁度" sortable />
            <el-table-column prop="country" label="发射国家" />
            <el-table-column prop="sat_type" label="卫星类型" />
          </el-table>
          <div class="page">
            <el-pagination layout="prev, pager, next" :total="total" @current-change="handleCurrentPageChange">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { getStrikeSatellites, gettargetStrike, getWeapons } from '@/api/dashboard'
import { useLayoutStore } from '@/store/modules/layout'
import { onMounted, ref, useTemplateRef } from 'vue'
import * as Cesium from 'cesium'
const store = useLayoutStore()

const cesiumRef = useTemplateRef('cesiumRef')
const MATERIAL_URL = import.meta.env.VITE_MATERIAL_URL
let viewer: Cesium.Viewer
const initViewer = () => {
  if (cesiumRef.value) {
    // 创建 Cesium Viewer 实例并禁用不需要的默认控件
    viewer = new Cesium.Viewer(cesiumRef.value, {
      scene3DOnly: false, // 启用 3D/2D 切换（这里允许 3D 模式）
      geocoder: false, // 关闭位置搜索控件
      homeButton: false, // 关闭回到默认视角按钮
      sceneModePicker: false, // 关闭视图模式切换器
      navigationHelpButton: false, // 关闭帮助按钮
      animation: false, // 关闭默认动画控件
      timeline: false, // 关闭默认时间轴控件（我们使用自定义时间轴）
      creditContainer: 'credit', // 版权信息容器
      fullscreenButton: false, // 关闭全屏按钮
      baseLayerPicker: false, // 关闭底图选择器
      baseLayer: false, // 不使用默认底图
      infoBox: false, // 关掉默认 InfoBox
    })

    // 添加切片影像图层（自定义瓦片服务器）
    viewer.imageryLayers.addImageryProvider(
      new Cesium.UrlTemplateImageryProvider({
        url: `${MATERIAL_URL}/tomcat/saveFile/{z}/{x}/{y}.png`, // 瓦片 URL 模板
        credit: 'credit', // 版权信息
      })
    )
    // 设置相机飞到中国上空
    const position = Cesium.Cartesian3.fromDegrees(104.0, 35.0, 20000000) // 经度、纬度、高度（单位：米）
    viewer.camera.setView({
      destination: position,
      orientation: {
        heading: 0.0, // 方向
        pitch: -Cesium.Math.PI_OVER_TWO, // 俯仰角
        roll: 0.0, // 横滚角
      },
    })

    // 添加大气层效果
    viewer.scene.globe.enableLighting = false
    viewer.scene.globe.atmosphereBrightnessShift = 0.1
    viewer.scene.globe.atmosphereHueShift = 0.0
    viewer.scene.globe.atmosphereSaturationShift = 0.0

    // 设置时间系统
    const startTime = Cesium.JulianDate.fromDate(new Date())
    const stopTime = Cesium.JulianDate.addSeconds(startTime, 86400, new Cesium.JulianDate()) // 24小时

    viewer.clock.startTime = startTime.clone()
    viewer.clock.stopTime = stopTime.clone()
    viewer.clock.currentTime = startTime.clone()
    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP
    viewer.clock.multiplier = 1.0

    listenClickEvents()
  }
}
const showThreatPanel = ref(false)
const showAssetsPanel = ref(false)
// 监听鼠标左键点击事件并处理实体选择
function listenClickEvents() {
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
  viewer.screenSpaceEventHandler.setInputAction(async function (event: Cesium.ScreenSpaceEventHandler.PositionedEvent) {
    const picked = viewer.scene.pick(event.position)
    if (!Cesium.defined(picked)) {
      showThreatPanel.value = false
      showAssetsPanel.value = false
      return
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
const showAssets = () => {
  showThreatPanel.value = true
}
const attackCountObj = ref<{ strikeDegree: number; threatDegree: number; days: number }>()
async function loadAttackCount() {
  if (store.activedTaskId) {
    const res = await gettargetStrike(store.activedTaskId)
    if (res.code === 200) {
      attackCountObj.value = res.data
    }
  }
}
const weapons = ref<Weapon[]>([])
const loadAssets = async () => {
  const res = await getWeapons()
  if (res.code === 200) {
    weapons.value = res.data.map((s) => {
      let lon: number = 0,
        lat: number = 0
      switch (s.province) {
        case '云南':
          {
            lon = 102.73
            lat = 25.05
          }
          break
        case '海南':
          {
            lon = 110.35
            lat = 20.02
          }
          break
        case '广东':
          {
            lon = 113.23
            lat = 23.17
          }
          break
        case '福建':
          {
            lon = 119.3
            lat = 26.08
          }
          break
        case '广西':
          {
            lon = 108.32
            lat = 22.82
          }
          break
        case '南海':
          {
            lon = 3
            lat = 108
          }
          break
      }
      return { ...s, lon, lat }
    })

    // cesium 地图加载资产
    loadAssetsOnMap()
  }
}
function loadAssetsOnMap(){
  for (const ass of weapons.value) {
    // viewer.
  }
}
const satelliteStrike = ref<SatelliteStrike[]>([])
const total = ref(0)
const handleCurrentPageChange = (page: number) => {
  loadSatelliteStrike(store.activedTaskId!, page, 5)
}
const loadSatelliteStrike = async (taskId: number, page: number, pageSize: number) => {
  const res = await getStrikeSatellites(taskId, page, pageSize)
  if (res.code === 200) {
    satelliteStrike.value = res.data.content
    total.value = res.data.totalElements
  }
}
onMounted(() => {
  initViewer()
  loadAttackCount()
  loadAssets()
  loadSatelliteStrike(store.activedTaskId!, 1, 5)
})
</script>
<style lang="scss" scoped>
.attack-container {
  .cesium-container {
    position: relative;
    height: calc(100vh - 110px);

    /* 1. 进入前：藏在左边 */
    .slide-enter-from {
      transform: translateX(-100%);
    }
    /* 2. 进入过程 & 离开过程：做动画 */
    .slide-enter-active,
    .slide-leave-active {
      transition: transform 0.5s ease-in-out;
    }
    /* 3. 离开后：再滑回去 */
    .slide-leave-to {
      transform: translateX(-100%);
    }

    .toolbox {
      padding: 0 5px;
      height: 30px;
      z-index: 1;
      position: absolute;
      top: 0;
      right: 0;
      display: flex;
      justify-content: end;
      gap: 5px;
      width: 100%;
    }
    .credit {
      display: none;
    }
    .attack-degree {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      z-index: 1;
      .count {
        display: flex;
        padding-top: 10px;
        gap: 5px;
        justify-content: space-between;
        & > div {
          background: rgba($color: #000000, $alpha: 0.5);
          display: flex;
          flex: 1;
          flex-direction: column;
          align-items: center;
          padding: 5px;
          width: 120px;
          & > span:first-child {
            font-size: 18px;
            font-weight: bold;
          }
        }
      }
    }
    .attck-assets {
      height: calc(100vh - 110px);
      overflow-y: scroll;
      overflow-x: hidden;
      position: absolute;
      left: 0;
      width: 350px;
      z-index: 1;
      .assets {
        .assets-l {
          background: #1f4a76;
          padding: 10px;
          font-size: 14px;
          .assets-l__title {
            display: flex;
            padding-bottom: 5px;
            align-items: center;
          }
          .assets-item {
            cursor: pointer;
            background: #164069;
            display: flex;
            flex-direction: column;
            gap: 5px;
            align-items: start;
            padding: 5px;
            margin-bottom: 5px;
            &:hover {
              background: rgb(50, 86, 128);
            }

            div {
              text-align: left;
              .tag-box {
                display: flex;
                flex-wrap: wrap;
                gap: 5px;
              }
              div {
                padding: 10px 0;
              }
            }
          }
        }
      }
    }
    .attck-satellite {
      position: absolute;
      bottom: 0;
      z-index: 1;
      .asset-grid-item {
        width: 100%;
        .page {
          background: #1f4a76;
          display: flex;
          justify-content: end;
        }
      }
    }
  }
}
</style>
